package editor
{
	import UIFree.ObjectEvent;
	
	import UIFree.uif_Timer;
	import UIFree.uif_component;
	
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	public class pi_photo extends pi_source {
		private var _rect: pi_rect;
		private var _lc: LoaderContext;
		private var _initRectSize: Point;
		private var _mask: uif_component;
		
		public static var RESELECT: String = 'RESELECT';
		
		public function pi_photo(parent:uif_component, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:String='white') {
			super(parent, ax, ay, awidth, aheight, styleClass);
			visible = false;
			_lc = new LoaderContext(true);
			_rect = new pi_rect(this, 0, 0, 20, 20);
			var _this: pi_photo = this;
			function l_resize(e: Event): void {
				app.dispatchEvent(new ObjectEvent(RESELECT, _this));
			}
			_rect.addEventListener(uif_component.DRAG, l_resize);
			_rect.addEventListener(uif_component.ROTATION, l_resize);
			_rect.addEventListener(uif_component.RESIZE, l_resize);
			_mask = new uif_component(this, 0, 0, width, height, 'mask');
			_rect.mask = _mask;
		}
		
		override protected function doLoad(e: Event): void {
			super.doLoad(e);
			resetSize(_initRectSize);
		}
		
		public function resetSize(initRectSize: Point): void {
			_initRectSize = initRectSize;
			var tRect: Point = _initRectSize.clone();
			tRect.x *= sourceScale;
			tRect.y *= sourceScale;
			_rect.x = (width  - tRect.x) / 2 + tRect.x / 2;
			_rect.y = (height - tRect.y) / 2 + tRect.y / 2;
			new uif_Timer(20, function(e: TimerEvent): void {
				visible = source.contentLoaderInfo.bytesLoaded > 0;
				_rect.reset(tRect);
			}, null, 1);
		}
		
		public function loadPhoto(url: String, initRectSize: Point): void {
			_source.load(new URLRequest(url), _lc);
			_initRectSize = initRectSize;
		}
		
		public function get rect(): pi_rect {
			return _rect;
		}
	}
}